package com.my.home.common.intercepter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by Al Sah-him on 2018/7/3.
 */
public class RequestIntercepter implements HandlerInterceptor{
    protected Logger logger= LoggerFactory.getLogger(RequestIntercepter.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        List<String> list=getList(httpServletRequest);
        if(list.size()>0){
            int max=list.get(0).length();
            for(int i=0;i<list.size();i++){
                if(list.get(i).length()>max){
                    max=list.get(i).length();
                }
            }
            if(max>500){
                logger.error("参数过长");
                return false;
            }
        }
        logger.info("参数认证通过");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    private List<String> getList(HttpServletRequest request){
        List<String> list=new ArrayList<>();
        Enumeration enumeration=request.getParameterNames();
        while (enumeration.hasMoreElements()){
            String name= (String) enumeration.nextElement();
            String value=request.getParameter(name);
            list.add(value);
        }
        return list;
     }
}
